import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../../shared/blade/blade-container-base";
import { BladeData } from "../../../../../shared/blade/blade-data";
import { Blade } from "../../../../../shared/blade/blade.model";
import { Command } from "../../../../../shared/toolbar.service";
import { DialogResult } from "../../../../../shared/dialog.service";
import { Scheme } from "../../../../../entity/scheme.model";
import { FaultAlarmEditComponent } from "../fault-alarm-edit/fault-alarm-edit.component"
import { Fault } from "../../../../../entity/fault.model";
import { FaultService } from "../../../../../service/fault.service";
import { AlarmCategory } from "../../../../../entity/alarm-category.model";
import { FaultLevel } from "../../../../../entity/fault-level.model";
import { AlarmCategoryService } from "../../../../../service/alarm-category.service";
import { TagService } from "../../../../../service/tag.service";
import { Tag } from "../../../../../entity/tag.model";
import { FaultLevelService } from "../../../../../service/fault_level.service";
import { TurbcomponentService } from "../../../../../service/turbcomponent.service";
import { TurbComponent } from "../../../../../entity/turbcomponent.model";
import { UploadComponent } from "../../fault-alarm/upload/upload.component";
import { ModelService } from '../../../../../service/model.service';

interface FaultData {
  faultCode: string,
  faultDesc: string,
  faultLevel: string,
  faultLevelColor: string,
  unAlarm: boolean,
  alarmCategory: string,
  turbComponent: string,
  tagName?: string,
}
interface ParentData {
  current: Scheme,
  tags: Tag[],
  alarmCategory: AlarmCategory[],
  faultLevel: FaultLevel[],
  turbComponentList: TurbComponent[]
}
@Component({
  selector: 'app-fault-alarm-list',
  templateUrl: './fault-alarm-list.component.html',
  styleUrls: ['./fault-alarm-list.component.css']
})
export class FaultAlarmListComponent extends BladeContainerBase<Scheme>{
  /**
   * 故障信息
   */
  faults: Fault[] = [];
  faultsFilter: Fault[] = [];
  faultsData: FaultData[] = [];
  faultsDataFilter: FaultData[] = [];
  alarmCategory: AlarmCategory[] = [];
  /**
   * 报警等级
   */
  faultLevel: FaultLevel[] = [];
  currentFault: Fault;
  /**
   * 报警类别
   */
  turbComponentList: TurbComponent[] = [];
  tags: Tag[] = [];

  //搜索关键词；
  sreachValue: string = "";
  //上传的文件
  file: File;
  constructor(
    private faultService: FaultService,
    private alarmCategoryService: AlarmCategoryService,
    private faultLevelService: FaultLevelService,
    private turbcomService: TurbcomponentService,
    private modelService: ModelService
  ) {
    super()
  }
  ngOnInit() {
    this.commands = [
      new Command("add", "添加", "fa fa-plus", "setofkey:insert", blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command("edit", "编辑", "fa fa-edit", "setofkey:update", blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command("delete", "删除", "fa fa-trash-o", "setofkey:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade)),
      new Command("delete", "导入", "fa fa-trash-o", "setofkey:delete", (blade, ev) => this.exeUploader(blade), blade => this.canExeUploader(blade)),
    ];
    if (this.currentEntity.multipleValue) {
      this.modelService.getTagByModelId(this.parentEntity.modelId)
        .then(res => {
  
          if (!res) return false;
          this.tags = [...res];
          if (!this.faultsData && this.faults) {
            this.getFaultsData()
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
    super.ngOnInit();

  }
  initData(): any {
    this.sreachValue = "";
    let alarmCategory = this.alarmCategoryService.getAlarmCategorys();
    let faultLevel = this.faultLevelService.getFaultLevels();
    let turbcomponent = this.turbcomService.getTurbComponents()
    Promise.all([alarmCategory, faultLevel, turbcomponent])
      .then(res => {
        if (res[0]) {
          this.alarmCategory = [...res[0]];
        }
        if (res[1]) {
          this.faultLevel = [...res[1]];
        }
        if (res[2]) {
          this.turbComponentList = [...res[2]];
        }
        this.faultService.getFaultsBySchemeId(this.currentEntity.schemeId)
          .then(res => {
            this.bladeData.isLoading = false;
            if (res) {

              this.faultsFilter = [...res];
              this.faults = this.faultsFilter;
              let faultsData: FaultData[] = [];
              if (this.currentEntity.multipleValue) {
                if (this.tags && this.tags.length) {
                  this.getFaultsData();
                } else {
                  this.modelService.getTagByModelId(this.parentEntity.modelId)
                    .then(res => {
                      if (!res) return false;
                      this.tags = [...res];
                      this.getFaultsData()
                    })
                    .catch(err => {
                      console.log(err)

                    })

                }
              } else {
                this.faults.forEach((fault, i) => {
                  this.faultLevel.filter(o => o.faultLevelId == fault.faultLevelId)
                  const faultData: FaultData = {
                    faultCode: fault.faultCode,
                    faultDesc: fault.faultDesc,
                    faultLevel: (this.faultLevel.filter(o => o.faultLevelId == fault.faultLevelId))[0].faultLevelName,
                    faultLevelColor: (this.faultLevel.filter(o => o.faultLevelId == fault.faultLevelId))[0].faultLevelColor,
                    unAlarm: fault.unAlarm,
                    alarmCategory: (this.alarmCategory.filter(o => o.alarmCategoryId == fault.alarmCategoryId))[0].alarmCategoryName,
                    turbComponent: ''
                    // turbComponent: (this.turbComponentList.filter(o => o.turbComponentId == fault.turbComponentId))[0].turbComponentName,
                  }
                  const turbComponents = this.turbComponentList.filter(o => o.turbComponentId == fault.turbComponentId);
                  if (turbComponents != null && turbComponents.length > 0) {
                    faultData.turbComponent = turbComponents[0].turbComponentName;
                  }
                  faultsData.push(faultData);

                })
                this.faultsDataFilter = faultsData;
                this.faultsData = [...this.faultsDataFilter];

              }

            }
          })
          .catch(err => {
            console.log(err)
          })
      })
      .catch(err => {
        console.log(err)
      })

  }
  getFaultsData() {
    let faultsData: FaultData[] = [];
    // console.log(this.faults)
    this.faults.forEach(fault => {
      let tagName: string = '';
      if (this.tags.filter(o => o.tagId == fault.tagId).length) {
        tagName = this.tags.filter(o => o.tagId == fault.tagId)[0].tagName;
      }


      let faultData: FaultData = {
        faultCode: fault.faultCode,
        faultDesc: fault.faultDesc,
        faultLevel: (this.faultLevel.filter(o => o.faultLevelId == fault.faultLevelId))[0].faultLevelName,
        faultLevelColor: (this.faultLevel.filter(o => o.faultLevelId == fault.faultLevelId))[0].faultLevelColor,
        unAlarm: fault.unAlarm,
        alarmCategory: (this.alarmCategory.filter(o => o.alarmCategoryId == fault.alarmCategoryId))[0] && ((this.alarmCategory.filter(o => o.alarmCategoryId == fault.alarmCategoryId))[0].alarmCategoryName),
        turbComponent: "",
        tagName: fault.tagId ? tagName : "",
      }
      if ((this.turbComponentList.filter(o => o.turbComponentId == fault.turbComponentId))[0]) {
        faultData.turbComponent = (this.turbComponentList.filter(o => o.turbComponentId == fault.turbComponentId))[0].turbComponentName;



      }
      if (fault.tagId) {
        fault.tagName = tagName;
      }
      faultsData.push(faultData);
      // console.log(faultData)
    })
    this.faultsDataFilter = faultsData;
    this.faultsData = [...this.faultsDataFilter];


  }
  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = "modelGroupingCreate";
    data.title = "创建一个故障信息";
    data.isClosingDisabled = false;
    let newData: Fault = {
      faultId: 0,
      schemeId: this.currentEntity.schemeId,
      faultLevelId: this.faultLevel[0].faultLevelId,
      turbComponentId: this.turbComponentList[0].turbComponentId,
      alarmCategoryId: this.alarmCategory[0].alarmCategoryId,
      unAlarm: false
    };
    let parentData: ParentData = {
      current: this.currentEntity,
      tags: this.tags,
      alarmCategory: this.alarmCategory,
      faultLevel: this.faultLevel,
      turbComponentList: this.turbComponentList
    }
    let createKeyBlade = this.bladeService.createBlade(FaultAlarmEditComponent, data, true, newData, parentData);
    this.bladeService.showBlade(createKeyBlade, this.currentBlade);
  }
  canExeAdd(blend: Blade): boolean {
    return true;
  }
  exeUploader(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = "upload";
    data.title = "导入";
    let parentData: ParentData = {
      current: this.currentEntity,
      tags: this.tags,
      alarmCategory: this.alarmCategory,
      faultLevel: this.faultLevel,
      turbComponentList: this.turbComponentList
    }
    let editKeyBlade = this.bladeService.createBlade(UploadComponent, data, false, this.currentFault, parentData);
    this.currentBlade.bladeService.showBlade(editKeyBlade, this.currentBlade);

  }
  canExeUploader(blend: Blade): boolean {
    return true;
  }





  exeEdit(blend: Blade): void {
    if (this.currentFault != undefined) {
      let data: BladeData = new BladeData();
      data.id = "standardCurveEdit";
      data.title = "故障信息";
      let parentData: ParentData = {
        current: this.currentEntity,
        tags: this.tags,
        alarmCategory: this.alarmCategory,
        faultLevel: this.faultLevel,
        turbComponentList: this.turbComponentList
      }
      let editKeyBlade = this.bladeService.createBlade(FaultAlarmEditComponent, data, false, this.currentFault, parentData);
      this.currentBlade.bladeService.showBlade(editKeyBlade, this.currentBlade);
    }
  }
  canExeEdit(blend?: Blade): boolean {
    return this.currentFault != null;
  }
  exeDelete(blend: Blade): void {
    let selectedKeys = this.getSelected();
    if (selectedKeys.length > 0) {
      this.dialogService
        .showConfirmationDialog("确认删除", "是否要删除选中项？")
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;
            this.faultService.batchDelete(selectedKeys.map(o => o.faultId))
              .then(res => {
                //if (res) {
                  super.refresh(this.currentEntity);
                //}
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }
  }
  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;
  }

  onSearchFaultName(value: string) {
    value = value.trim();
    setTimeout(() => {
      if (value == "") {
        this.faults = [...this.faultsFilter]
        this.faultsData = [...this.faultsDataFilter];
      } else {
        this.faultsData = this.faultsDataFilter.filter(o => o.faultDesc.indexOf(value) > -1);
        this.faults = this.faultsFilter.filter(o => o.faultDesc.indexOf(value) > -1);
      }
    }, 1000);

  }
  getSelected(): Fault[] {
    if (this.faults && this.faults.length > 0) {
      let filter = this.faults.filter(ref => ref.isChecked);
      return filter == null ? [] : filter;
    }
    return [];
  }
  onSeletedChange(selectedKey: Fault) {
    this.currentFault = selectedKey;
  }
  onItemCheack(event: HTMLInputElement, key: Fault) {
    key.isChecked = event.checked;
  }
  onAllCheack(event: HTMLInputElement) {
    if (this.faults.length > 0) {
      for (let i = 0; i < this.faults.length; i++) {
        this.faults[i].isChecked = event.checked;
      }
    }
  }
}



// WEBPACK FOOTER //
// ./src/app/module/basic/model/fault-alarm/fault-alarm-list/fault-alarm-list.component.ts